<?php


namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\Model\Users;
use App\Model\Company;
use App\Model\Dangerrecords;
use App\Model\AdminUserRoleRelation;
use App\Model\Message;
use App\Model\MessageText;

use PhpOffice\PhpWord\TemplateProcessor;
use App\Services\Export\WordChoose;
use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\SimpleType\TblWidth;
use Storage;

use DB;

class DangerrecordsController extends Controller
{


    /**
     * 文件上传-图片/视频
     * 公共接口已存在
     * /api/upload/uploadimg
     * /api/upload/uploadmp4
     */


     /**
      * 随手拍记录列表
      *page  limit 
     */

     public function list(Request $request){
         
        // 查询当前登录人提交的全部随手拍图片记录
        $query = Dangerrecords::with(['assign_user','users'])->where('is_delete',1);
        if($request['name']){
            // 模糊查询
            $query->where('content','like','%'.$request['name'].'%');
        }
        $list = $query->paginate($request->get('limit',10))->toArray();
      //   dump($list );exit;
        foreach($list['data'] as &$v){
         $images = explode(',',$v['images']);
         if($images){
            foreach($images as &$iv){
               // $iv = 'http://'.$_SERVER['SERVER_NAME'].$iv;
            }
         }
          $v['images'] = $images;
         // 查询被查询人
         $v['assign_user_name'] = Users::where('id',$v['assign_user_id'])->pluck('name');
         if(!empty($v['video'])){
            // $v['video'] = 'http://'.$_SERVER['SERVER_NAME'].$v['video'];
         }
        }
      //   return response()->json(array('data'=>$list->items(),'message'=>'查询成功','code'=>200),200);
      $data = [
			'code' => 0,
			'msg'   => '请求成功',
			'count' => $list['total'],
			'data'  => $list['data']
		];
     return response()->json($data);
     }

     /**
      * 获取单条数据
      * 图片是多图上传，视频是单个
     */
    public function data(Request $request){
      if(empty($request['id'])){
         return response()->json(array('data'=>array(),'message'=>'ID不能为空','code'=>400),400);
      }
      $data = Dangerrecords::findorfail($request['id']);
      $data['user_name'] = Users::where('id',$data['user_id'])->pluck('name')->first();

      $images = explode(',',$data['images']);
      if($images){
         foreach($images as &$iv){
            // $iv = 'http://'.$_SERVER['SERVER_NAME'].$iv;
         }
      }

      $data['images'] = $images;
      if(!empty($data['video'])){
         // $data['video'] = 'http://'.$_SERVER['SERVER_NAME'].$data['video'];
      }
      
      return response()->json(array('data'=>$data,'message'=>'查询成功','code'=>200),200);
    }

    /**
      * 添加/修改随手拍记录
      * 图片是多图上传，用，分隔，视频是单个
     */
   //  public function edit(Request $request){

   //    $rules = [
   //       'content' => 'required',
   //       'lng' => 'required',
   //       'lat' => 'required',
   //       'address' => 'required',
   //    ];
   //    $messages = [
   //          'content.required' => '描述未填写',
   //          'lng.required' => '经度不能为空',
   //          'lat.required' => '维度不能为空',
   //          'address.required' => '地址信息不能为空',
   //    ];
   //    $validator = Validator::make($request->all(),$rules,$messages);
   //    if ($validator->fails()) {
   //          return response()->json(['code'=>0,'msg' => $validator->errors()->first()], 200);
   //    }


   //    if(empty($request['id'])){
	// 		// 新增
	// 		$model = new Dangerrecords();
	// 	}else{
	// 		// 编辑
	// 		$model = Dangerrecords::findorfail($request['id']);
	// 		if(!$model){
	// 			return response()->json(array('data'=>array(),'message'=>'数据不存在','code'=>400),400);
	// 		}
	// 	}

   //    $company_id = Company::where('userId',Auth::guard('admin')->user()id)->pluck('id');
	// 	$model->images = $request['images'];
	// 	$model->video = $request['video'];
	// 	$model->content = $request['content'];
	// 	$model->type = !empty($request['images'])? 1 : 2;
	// 	$model->lng = $request['lng'];
	// 	$model->lat = $request['lat'];
	// 	$model->address = $request['address'];
	// 	$model->user_id = Auth::guard('admin')->user()id;
	// 	$model->company_id = $company_id;
	// 	$model->save();
   //    return response()->json(array('data'=>array(),'message'=>'操作成功','code'=>200),200);
   //  }

     /**
      * 删除随手拍记录
     */

     public function delete(Request $request){
      if(empty($request['id'])){
         return response()->json(array('data'=>array(),'message'=>'ID不能为空','code'=>400),400);
      }
      $model = Dangerrecords::findorfail($request['id']);
      $model->is_delete = 2;
      $model->save();
      return response()->json(array('data'=>array(),'message'=>'删除成功','code'=>200),200);
     }

   //   获取用户列表

   public function user_list(Request $request){

      // dump($user_ids);exit;
      if($request['name']){
         $list = Users::whereIn('type',[1])->where('name','like','%'.$request['name'].'%')->select(['id','name'])->get();
      }else{
         $list = Users::whereIn('type',[1])->select(['id','name'])->get();
      }
      
      return response()->json(array('data'=>$list,'message'=>'查询成功','code'=>200),200);
   }


   //   隐患信息指派
   public function user_assign(Request $request){
      if(empty($request['id'])){
         return response()->json(array('data'=>array(),'message'=>'ID不能为空','code'=>400),400);
      }
      if(empty($request['user_id'])){
         return response()->json(array('data'=>array(),'message'=>'被指派用户ID不能为空','code'=>400),400);
      }
      $record_data = Dangerrecords::findorfail($request['id']);
      // dump($request['id']);exit;
      // 先插入messagetext表再更新message表

      DB::beginTransaction();

        try{
            $mt = [
               'title'=>'随手拍现场查看人指派提醒',
               'content'=>$record_data->content,
               'attachment'=>!empty($record_data->images) ? $record_data->images : $record_data->video,
               'file_name'=>!empty($record_data->images)?'image':(!empty($record_data->video)?'video':''),
               'add_time'=>time(),
               'type'=>3
            ];
            $text_id = MessageText::insertGetId($mt);

            if($text_id) {
               //  插入message的信息

               $message = [
                  'from_id'=>Auth::guard('admin')->user()->id,
                  'to_id'=>$request['user_id'],
                  'message_id'=>$text_id
               ];
               $res = Message::insertGetId($message);
               if($res){
                  $record_data->assign_status = 2;
                  $record_data->assign_user_id = $request['user_id'];
                  $record_data->save();
               }
            }
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            $res_arr["code"] = 402;
            $res_arr["message"] = '请勿重复指派';
            return response()->json($res_arr);
        }
        $res_arr["data"] = [];
        $res_arr["code"] = 200;
        $res_arr["message"] = '指派成功';
        return response()->json($res_arr);

   }


}